package jdbmaplite.connection.impl;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

import javax.sql.DataSource;

import jdbmaplite.connection.DBConnectionFactory;

import com.mchange.v2.c3p0.DataSources;

public class C3P0ConnectionFactory extends DBConnectionFactory {

	private DataSource connectionPool = null;

	/**
	 * Default constructor.
	 * 
	 * @param driver
	 *            String
	 * @param url
	 *            String
	 * @param user
	 *            String
	 * @param password
	 *            String
	 * @throws ClassNotFoundException
	 * @throws SQLException
	 */
	public C3P0ConnectionFactory(String driver, String url, String user,
			String password) throws ClassNotFoundException, SQLException {
		super(driver, url, user, password);
		loadDriver();
		connectionPool = DataSources.unpooledDataSource(url, user, password);
	}

	public void loadProperties(Properties properties) throws SQLException {
		properties.remove("driverClass");
		properties.remove("jdbcUrl");
		properties.remove("user");
		properties.remove("password");
		connectionPool = DataSources.pooledDataSource(connectionPool,
				properties);
	}

	public Connection getConnection() throws SQLException {
		return connectionPool.getConnection();
	}

	public void destroy() throws SQLException {
		DataSources.destroy(connectionPool);
	}

	/**
	 * Load Driver
	 * 
	 * @throws ClassNotFoundException
	 */
	public void loadDriver() throws ClassNotFoundException {
		Class.forName(getDriver());
	}

	/**
	 * Get ConnectionPool
	 * 
	 * @return DataSource
	 */
	public DataSource getConnectionPool() {
		return connectionPool;
	}

	/**
	 * Set ConnectionPool
	 * 
	 * @param connectionPool
	 *            DataSource
	 */
	public void setConnectionPool(DataSource connectionPool) {
		this.connectionPool = connectionPool;
	}

}